﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using WeifenLuo.WinFormsUI.Docking;

namespace Bing.Studio
{
    public partial class FrmMain : Form
    {
        private FrmDatabaseExplorer _frmDatabaseExp;
        private FrmWindowsExplorer _frmWindowsExp;
        private FrmOutput _frmOutput;

        public FrmMain()
        {
            InitializeComponent();
        }

        /****************************************************************************************************/

        #region /*自定义方法*/

        private void ShowDatabaseExplorer()
        {
            if (_frmDatabaseExp == null)
            {
                _frmDatabaseExp = CreateWindow<FrmDatabaseExplorer>();
                _frmDatabaseExp.ClickMenuEvent += new ClickMenuHandler(_frmDatabaseExp_ClickMenuEvent);
            }
            if (_frmDatabaseExp.IsHidden)
            {
                _frmDatabaseExp.Show(this.dockPanel1, DockState.DockLeft);
            }
        }

        void _frmDatabaseExp_ClickMenuEvent(object sender, DatabaseExplorerEventArgs e)
        {
            switch (e.ActionType)
            { 
                case DatabaseExplorerActionType.CodeGenerator:
                    var frmCodeGenerator = CreateWindow<FrmCodeGenerator>(
                        e.Database, 
                        e.CommandObject, 
                        e.ConnectionString, 
                        e.ProviderName);
                    frmCodeGenerator.TabText = e.CommandObject;
                    frmCodeGenerator.Show(this.dockPanel1);
                    ShowWindowsExplorer();
                    break;
                case DatabaseExplorerActionType.SQLQuery:
                    var frmQueryBuilder = CreateWindow<FrmQueryBuilder>(e.ConnectionString, e.CommandObject);
                    frmQueryBuilder.Show(this.dockPanel1);
                    break;
                case DatabaseExplorerActionType.InsertScript:
                    var frmInsertBuilder = CreateWindow<FrmInsertScript>(e.ConnectionString, e.CommandObject);
                    frmInsertBuilder.Show(this.dockPanel1);
                    break;
                default:
                    throw new Exception("Unknown");
            }
        }

        private void ShowWindowsExplorer()
        {
            if (_frmWindowsExp == null)
            {
                _frmWindowsExp = CreateWindow<FrmWindowsExplorer>();
                _frmWindowsExp.ClickFileItemEvent += new ClickFileItemHandler(_frmWindowsExp_OnClickFileEvent);
            }
            if (_frmWindowsExp.IsHidden)
            {
                _frmWindowsExp.Show(this.dockPanel1, DockState.DockRight);
            }
        }

        void _frmWindowsExp_OnClickFileEvent(object sneder, ResourceExplorerEventArgs e)
        {
            if (dockPanel1.ActiveDocument is FrmCodeGenerator)
            { 
                (dockPanel1.ActiveDocument as FrmCodeGenerator).FillTemplateContent(File.ReadAllText(e.FullName, Encoding.Default));
            }
        }

        private void ShowOutput(string msg = "")
        {
            if (_frmOutput == null)
            {
                _frmOutput = new FrmOutput();
            }
            if (_frmOutput.IsHidden)
            {
                _frmOutput.Show(this.dockPanel1, DockState.DockBottom);
            }
            if (!String.IsNullOrEmpty(msg))
            {
                _frmOutput.OutputMessage(msg);
            }
        }

        private T CreateWindow<T>(params object[] args) where T : BaseForm
        {
            T winForm;
            if (args.Length > 0)
            {
                winForm = Activator.CreateInstance(typeof(T), args) as T;
            }
            else
            {
                winForm = Activator.CreateInstance<T>();
            }

            winForm.NotificationEvent += frm_NotificationEvent;

            return winForm;
        }

        private void frm_NotificationEvent(object sender, NotificationEventArgs e)
        {
            ShowOutput(e.Message);
        }

        private void ToolStripPanelSort()
        {
            for (var i = 0; i < toolStripPanel1.Controls.Count; i++)
            {
                if (i == 0)
                {
                    toolStripPanel1.Controls[i].Location = new Point(0, 0);
                }
                else
                {
                    var prev = toolStripPanel1.Controls[i - 1];
                    toolStripPanel1.Controls[i].Location = new Point(prev.Width + prev.Location.X, 0);
                }
            }
        }

        private void AddTemplateEditToDocument(FileInfo file = null)
        {
            FrmTemplateEdit frm = null;
            if (file == null)
            {
                frm = CreateWindow<FrmTemplateEdit>();
            }
            else
            {
                frm = CreateWindow<FrmTemplateEdit>(file);
            }
            frm.Show(this.dockPanel1);
        }

        private void SaveDocument(bool isSaveAs = false)
        {
            if (this.dockPanel1.ActiveDocument is FrmTemplateEdit)
            {
                var frm = this.dockPanel1.ActiveDocument as FrmTemplateEdit;
                if (frm.IsSaved && !isSaveAs)
                {
                    frm.Save();
                }
                else
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.FileName = frm.Text;
                    dialog.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory(), "App_Template");
                    dialog.Filter = "*tt|*.tt|所有文件|*.*";
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        frm.SaveAs(dialog.FileName);
                    }
                }
            }
        }

        private void OpenDocument()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "*.tt|*.tt|*.sql|*.sql|所有文件|*.*";
            dialog.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory(), "App_Template");
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                FileInfo file = new FileInfo(dialog.FileName);
                switch (file.Extension)
                { 
                    case ".tt":
                        AddTemplateEditToDocument(file);
                        break;
                }
            }
        }

        #endregion

        /****************************************************************************************************/

        private void FrmMain_Load(object sender, EventArgs e)
        {
            ShowDatabaseExplorer();
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            ShowDatabaseExplorer();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            ShowWindowsExplorer();
        }

        private void tsmiShuChu_Click(object sender, EventArgs e)
        {
            ShowOutput();
        }

        private void dockPanel1_ActiveDocumentChanged(object sender, EventArgs e)
        {
            #region /* Active document is FrmCodeGenerator */
            if (dockPanel1.ActiveDocument is FrmCodeGenerator)
            {
                if (!toolStripPanel1.Controls.ContainsKey("tsCodeRun"))
                {
                    ToolStrip tStrip = new ToolStrip();
                    tStrip.Name = "tsCodeRun";
                    tStrip.Items.Add("运行", Bing.Studio.Properties.Resources._20120804083108776_easyicon_cn_24);
                    tStrip.BackColor = Color.FromName("ButtonFace");
                    tStrip.Click += new EventHandler(tStrip_Click);
                    toolStripPanel1.Join(tStrip);
                    ToolStripPanelSort();
                }
            }
            else
            {
                toolStripPanel1.Controls.RemoveByKey("tsCodeRun");
                ToolStripPanelSort();
            }
            #endregion

            if (dockPanel1.ActiveDocument is FrmTemplateEdit)
            {
                toolStripButton3.Enabled = true;
                tsmiBaoCun.Enabled = true;
                tsmiLingCunWei.Enabled = true;
            }
            else
            {
                toolStripButton3.Enabled = false;
                tsmiBaoCun.Enabled = false;
                tsmiLingCunWei.Enabled = false;
            }
        }

        void tStrip_Click(object sender, EventArgs e)
        {
            if (dockPanel1.ActiveDocument is FrmCodeGenerator)
            {
                (dockPanel1.ActiveDocument as FrmCodeGenerator).RunCodeGenerator();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            AddTemplateEditToDocument();
        }

        private void tsmiXinJIanTt_Click(object sender, EventArgs e)
        {
            AddTemplateEditToDocument();
        }

        private void tsmiBaoCun_Click(object sender, EventArgs e)
        {
            SaveDocument();
        }

        private void tsmiLingCunWei_Click(object sender, EventArgs e)
        {
            SaveDocument(true);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            SaveDocument();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            OpenDocument();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenDocument();
        }

       
        /****************************************************************************************************/
    }
}
